package com.whf.aspect;

import com.whf.constant.RedisConstant;
import com.whf.exception.SellerAuthorizeException;
import com.whf.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 验证是否登陆的aop切面
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("execution(public * com.whf.Controller.Seller*.*(..))&&!execution(public * com.whf.Controller.SellerUserController.*(..))")
    public void verify(){
    }
    @Before("verify()")
    public void doVerify(){
        ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //查询cookie中的token
        Cookie cookie = CookieUtil.get(request, "token");
        if(cookie==null){
            log.info("[验证是否登陆] cookie中查询不到token");
            throw new SellerAuthorizeException();
        }
        //查询redis中的token
        String s = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if(StringUtils.isEmpty(s)){
            log.info("[验证是否登陆] redis中查询不到token");
            throw new SellerAuthorizeException();
        }

    }

}
